<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入等级"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="下级编码" prop="next_level_code">
        <el-input
          v-model="queryParams.next_level_code"
          placeholder="请输入对应下一级专业编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业资格" prop="qualification_skill_level">
        <el-input
          v-model="queryParams.qualification_skill_level"
          placeholder="请输入职业资格(职业技能等级)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="培养目标" prop="training_objective">
        <el-input
          v-model="queryParams.training_objective"
          placeholder="请输入培养目标"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="学习年限" prop="study_period">
        <el-input
          v-model="queryParams.study_period"
          placeholder="请输入学习年限"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="对应上级编码" prop="upper_level_code">
        <el-input
          v-model="queryParams.upper_level_code"
          placeholder="请输入对应上一级专业编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属大类ID" prop="major_category_id">
        <el-input
          v-model="queryParams.major_category_id"
          placeholder="请输入所属大类ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:major:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:major:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportTemplate"
        >
          <Icon icon="ep:download" class="mr-5px" /> 下载模板
        </el-button>
        <el-button
          type="success"
          plain
          @click="openImport"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['eval:major:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="等级" align="center" prop="level" />
      <el-table-column label="培养目标" align="center" prop="training_objective" />
      <el-table-column label="学习年限" align="center" prop="study_period" />
      <el-table-column label="职业能力" align="center" prop="vocational_competence" />
      <el-table-column label="对应或相关职业（工种）" align="center" prop="corresponding_occupation" />
      <el-table-column label="教学内容与要求" align="center" prop="curriculum_content" />
      <el-table-column label="对应上一级专业编码" align="center" prop="upper_level_code" />
      <el-table-column label="对应下一级专业编码" align="center" prop="next_level_code" />
      <el-table-column label="职业资格(职业技能等级)" align="center" prop="qualification_skill_level" />
      <el-table-column label="所属大类ID" align="center" prop="major_category_id" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:major:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['eval:major:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MajorForm ref="formRef" @success="getList" />

  <!-- 导入对话框 -->
  <el-dialog v-model="importDialogVisible" title="导入专业" width="450px">
    <el-form :model="importForm" ref="importFormRef" label-width="80px">
      <el-form-item label="文件" prop="file" required>
        <el-upload
          v-model:file-list="importFileList"
          :limit="1"
          :action="''"
          :auto-upload="false"
          :on-exceed="handleUploadExceed"
          :on-change="handleUploadChange"
          :before-remove="() => { importForm.file = undefined; return true }"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              请上传Excel格式文件(.xlsx, .xls)
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="更新已有">
        <el-switch v-model="importForm.updateSupport" />
      </el-form-item>
      <el-form-item label="多工作表">
        <el-switch v-model="importForm.multipleSheets" />
        <div class="el-upload__tip">
          开启后将读取Excel文件中的所有工作表数据
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="importDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitImport" :loading="importLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MajorApi, MajorVO } from '@/api/eval/major'
import MajorForm from './MajorForm.vue'

/** 专业管理 列表 */
defineOptions({ name: 'Major' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MajorVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  level: undefined,
  training_objective: undefined,
  study_period: undefined,
  vocational_competence: undefined,
  corresponding_occupation: undefined,
  curriculum_content: undefined,
  upper_level_code: undefined,
  next_level_code: undefined,
  qualification_skill_level: undefined,
  major_category_id: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 导入相关变量
const importDialogVisible = ref(false) // 导入对话框的显示隐藏
const importFormRef = ref() // 导入的表单
const importFileList = ref([]) // 导入的文件列表
const importForm = reactive({ // 导入的参数
  updateSupport: false,
  multipleSheets: false, // 添加多工作表支持选项
  file: undefined
})
const importLoading = ref(false) // 导入的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 输出查询参数，帮助排查问题
    console.log('查询参数:', queryParams)
    const data = await MajorApi.getMajorPage(queryParams)
    // 添加调试信息
    console.log('获取到的专业管理数据:', data)
    console.log('数据列表:', data.list)
    console.log('数据总数:', data.total)
    
    // 检查第一条数据的字段
    if (data.list && data.list.length > 0) {
      console.log('第一条数据详情:', data.list[0])
    }
    
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  // 添加调试信息
  console.log('搜索参数:', queryParams)
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  // 添加调试信息
  console.log('重置查询参数')
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MajorApi.deleteMajor(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除专业管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    for (const id of checkedIds.value) {
      await MajorApi.deleteMajor(id)
    }
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: MajorVO[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MajorApi.exportMajor(queryParams)
    download.excel(data, '专业管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

/** 导入按钮操作 */
const openImport = () => {
  importDialogVisible.value = true
}

/** 弹出导入窗口 */
const handleImportTemplate = async () => {
  try {
    const data = await MajorApi.importTemplate()
    download.excel(data, '专业管理导入模板.xls')
  } catch {}
}

/** 上传文件超过数量限制 */
const handleUploadExceed = () => {
  message.error('最多只能上传一个文件')
}

/** 上传文件改变 */
const handleUploadChange = (file: any) => {
  importForm.file = file.raw
}

/** 提交导入 */
const submitImport = async () => {
  // 校验
  if (!importForm.file) {
    message.error('请选择文件')
    return
  }
  
  // 添加文件类型检查
  const fileName = importForm.file.name.toLowerCase();
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    message.error('请选择Excel格式文件(.xlsx, .xls)')
    return
  }
  
  try {
    importLoading.value = true
    // 设置表单
    const data = new FormData()
    data.append('file', importForm.file)
    data.append('updateSupport', importForm.updateSupport)
    data.append('multipleSheets', importForm.multipleSheets) // 添加多工作表参数
    
    // 添加调试输出
    console.log('上传文件：', importForm.file)
    console.log('文件名：', importForm.file.name)
    console.log('文件大小：', importForm.file.size)
    console.log('文件类型：', importForm.file.type)
    console.log('是否更新：', importForm.updateSupport)
    console.log('是否多工作表：', importForm.multipleSheets)
    
    // 发起导入
    const res = await MajorApi.importMajor(data)
    console.log('导入响应：', res)
    
    if (res && res.data) {
      message.success(`导入成功！创建 ${res.data.createCount} 条数据！更新 ${res.data.updateCount} 条数据！`)
      if (res.data.failures && res.data.failures.length > 0) {
        console.warn('导入失败记录：', res.data.failures)
        message.warning(`有 ${res.data.failures.length} 条数据导入失败，请查看控制台`)
      }
    } else {
      message.success('导入完成')
    }
    
    // 关闭弹窗
    importDialogVisible.value = false
    // 初始化表单
    importForm.file = undefined
    importFileList.value = []
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('导入失败:', error)
    message.error('导入失败: ' + (error.message || '未知错误'))
  } finally {
    importLoading.value = false
  }
}
</script>